//
//  iOSGLESView.m
//  GSEngine
//
//  Created by Александр on 25.01.14.
//  Copyright (c) 2014 SNK. All rights reserved.
//

#import "iOSGLESView.h"
#import "iOSAppDelegate.h"
#include <GSEngine/GSEngine.h>

@implementation iOSGLESView

-(BOOL)isInit{
    m_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
    [EAGLContext setCurrentContext:m_context];
    
    m_animInterval = 1.0/60.0;
    m_animTimer = nil;
    m_useDepthBuffer = false;//temporary disable using depth buffer
    return YES;
}

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    return [self isInit] ? self : nil;
}

+(Class)layerClass
{
    return [CAEAGLLayer class];
}

-(void)renderLoopEvent:(NSTimer*)sender{
    if (sender == m_animTimer){
        if (m_animTimer)
            [self render];
    }
}

-(void)layoutSubviews{
    // удалить буферы
    [self deleteBuffers];
    // создать буферы
    [self createBuffers];
    // отрендерить
    [self render];
}

-(void)render{
    [[iOSAppDelegate getInstance] render];
    [m_context presentRenderbuffer:GL_RENDERBUFFER];
}

-(void)startAnimation{
    if (m_animTimer)
        return;
 
    m_animTimer = [NSTimer scheduledTimerWithTimeInterval:m_animInterval
                                                target:self
                                              selector:@selector(renderLoopEvent:)
                                              userInfo:nil
                                               repeats:YES];
}

-(void)createBuffers{
    // init frame buffer
    glGenFramebuffers(1, &m_frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
    // init render color buffer
    glGenRenderbuffers(1, &m_renderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer);
    [m_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];
    // attahment buffers
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_renderBuffer);
    // get render buffer size
    GLint width;
    GLint height;
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
    // init depth buffer if needed
    if (m_useDepthBuffer) {
        glGenRenderbuffers(1, &m_depthBuffer);
        glBindRenderbuffer(1, m_depthBuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthBuffer);
    }
    // checking errors
    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        NSLog(@"failed to make buffer: %x", status);
    }
}

-(void)deleteBuffers{
    glDeleteFramebuffers(1, &m_frameBuffer);
    glDeleteRenderbuffers(1, &m_renderBuffer);
    if (m_useDepthBuffer) {
        glDeleteRenderbuffers(1, &m_depthBuffer);
    }
}

-(void)useDepthBuffer{
    if (m_useDepthBuffer) {
        glBindRenderbuffer(1, m_depthBuffer);
    }
    else
        NSLog(@"There is no depth buffer");
}

-(void)discardDepthBuffer{
    if (m_useDepthBuffer) {
        const GLenum discards[] = {GL_DEPTH_ATTACHMENT};
        glBindFramebuffer(GL_FRAMEBUFFER, m_depthBuffer);
        glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, discards);
    }
    else
        NSLog(@"There is no depth buffer");
}

- (void) touchesBegan:(NSSet*) touches withEvent:(UIEvent*) event
{
	[[iOSAppDelegate getInstance] touchesBegan:touches withEvent:event];
}

- (void) touchesMoved:(NSSet*) touches withEvent:(UIEvent*) event
{
	[[iOSAppDelegate getInstance] touchesMoved:touches withEvent:event];
}

- (void) touchesEnded:(NSSet*) touches withEvent:(UIEvent*) event
{
	[[iOSAppDelegate getInstance] touchesEnded:touches withEvent:event];
}

- (void) touchesCancelled:(NSSet*) touches withEvent:(UIEvent*) event
{
	[[iOSAppDelegate getInstance] touchesCancelled:touches withEvent:event];
}

@end
